package zz.Dao;

import zz.javabean.User;
import zz.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
//    public List<User> findAll() throws SQLException {
//        Connection conn = null;
//        PreparedStatement stmt = null;
//        ResultSet rs = null;
//        List<User> userList = new ArrayList<>();
//        String sql = "SELECT*FROM tb_user";
//        try {
//            conn = DBUtil.getConnection();
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        }
//        stmt = conn.prepareStatement(sql);
//        rs = stmt.executeQuery();
//        while(rs.next()){
//            User user = new User();
//            user.setId(rs.getInt(1));
//            user.setUsername(rs.getString(2));
//            user.setPassword(rs.getString(3));
//            userList.add(user);
////            return userList;
//        }
//        return userList;
//    }
    public User findUser(String name)  {
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;
        User user = new User();
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT*FROM tb_user WHERE username=?";
            st = conn.prepareStatement(sql);
            st.setString(1, name);
            rs = st.executeQuery();
            while (rs.next() && rs.getRow() == 1) {
                if (rs.getString(2) != null && rs.getString(2).equals(name)) {
                    user.setId(rs.getInt(1));
                    user.setUsername(rs.getString(2));
                    user.setPassword(rs.getString(3));
                    return user;
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                DBUtil.closeAll(rs,st,conn);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return user;
    }
}
